package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.datatransfer.FlavorMap;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    private final static String KEY = "dish_";



    @Autowired
    private  DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品和口味的数据
     * @param dishDTO
     */
    @Override
    @Transactional
    public void saveWithFlavour(DishDTO dishDTO) {
        //属性赋值
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        // 处理图片URL
        String image = dish.getImage();
        if (image != null && !image.startsWith("http")) {
            // 如果图片路径不是完整URL，则构建完整的OSS访问路径
            dish.setImage("https://sky-take-out-luzhijin.oss-cn-hangzhou.aliyuncs.com/" + image);
        }
        //向菜品表插入一条数据
        dishMapper.insert(dish);
        //获取菜品id
        long id=dish.getId();
        //向口味表插入数据（可能有多个）
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors!=null && flavors.size()>0){
            flavors.forEach(dishFlavor -> {
                //给每一个id赋值
                dishFlavor.setDishId(id);
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    public PageResult pageResult(DishPageQueryDTO dishPageQueryDTO) {
        // 生成缓存键，包含查询参数
        String cacheKey = generateCacheKey(dishPageQueryDTO);
        
        // 先从Redis缓存中查询
        PageResult cachedResult = (PageResult) redisTemplate.opsForValue().get(cacheKey);
        if (cachedResult != null) {
            log.info("从缓存中获取菜品分页数据: {}", cacheKey);
            return cachedResult;
        }
        
        // 缓存中没有数据，从数据库查询
        log.info("缓存中没有数据，从数据库查询菜品分页数据");
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page=dishMapper.pageQuery(dishPageQueryDTO);
        
        // 确保返回完整的图片URL
        List<DishVO> dishList = page.getResult();
        if (dishList != null && !dishList.isEmpty()) {
            for (DishVO dishVO : dishList) {
                String image = dishVO.getImage();
                if (image != null && !image.startsWith("http")) {
                    // 如果图片路径不是完整URL，则构建完整的OSS访问路径
                    dishVO.setImage("https://sky-take-out-luzhijin.oss-cn-hangzhou.aliyuncs.com/" + image);
                }
                
                // 为每个菜品查询口味信息
                List<DishFlavor> flavors = dishFlavorMapper.getBydishId(dishVO.getId());
                dishVO.setFlavors(flavors);
            }
        }
        
        PageResult result = new PageResult(page.getTotal(), dishList);
        
        // 将查询结果存入缓存，设置过期时间为30分钟
        redisTemplate.opsForValue().set(cacheKey, result, 30, java.util.concurrent.TimeUnit.MINUTES);
        log.info("菜品分页数据已存入缓存: {}", cacheKey);
        
        return result;
    }
    
    /**
     * 生成缓存键
     * @param dishPageQueryDTO
     * @return
     */
    private String generateCacheKey(DishPageQueryDTO dishPageQueryDTO) {
        StringBuilder keyBuilder = new StringBuilder(KEY);
        keyBuilder.append("page_");
        keyBuilder.append(dishPageQueryDTO.getPage());
        keyBuilder.append("_size_");
        keyBuilder.append(dishPageQueryDTO.getPageSize());
        
        if (dishPageQueryDTO.getName() != null && !dishPageQueryDTO.getName().isEmpty()) {
            keyBuilder.append("_name_").append(dishPageQueryDTO.getName());
        }
        if (dishPageQueryDTO.getCategoryId() != null) {
            keyBuilder.append("_category_").append(dishPageQueryDTO.getCategoryId());
        }
        if (dishPageQueryDTO.getStatus() != null) {
            keyBuilder.append("_status_").append(dishPageQueryDTO.getStatus());
        }
        
        return keyBuilder.toString();
    }

    /**
     * 菜品批量删除
     * @param ids
     */
    @Transactional
    @Override
    public void delete(List<Long> ids) {
        //判断当前菜品是否能够删除
        for (Long id : ids) {
            Dish dish = dishMapper.getByid(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //当前菜品属于售卖中不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断菜品是否被某个套餐关联
        List<Long> setmealIdsBySetmealDishId = setmealDishMapper.getSetmealIdsBySetmealDishId(ids);
        if (setmealIdsBySetmealDishId != null && setmealIdsBySetmealDishId.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品表中的菜品数据
        dishMapper.deleteByids(ids);
        //删除菜品关联的口味数据
        dishFlavorMapper.deleteBydishIds(ids);
    }

    /**
     * 根据id查询菜品和口味数据
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavour(Long id) {
        //创建对象
        DishVO dishVO = new DishVO();
        //查询菜品表
        Dish dish = dishMapper.getByid(id);
        //查询口味表
        List<DishFlavor>  dishFlavor= dishFlavorMapper.getBydishId(id);

        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavor);
        // 确保返回完整的图片URL
        String image = dishVO.getImage();
        if (image != null && !image.startsWith("http")) {
            // 如果图片路径不是完整URL，则构建完整的OSS访问路径
            dishVO.setImage("https://sky-take-out-luzhijin.oss-cn-hangzhou.aliyuncs.com/" + image);
        }
        return dishVO;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //修改菜品表
        dishMapper.update(dish);
        //修改口味表（先删除原先的口味然后重新插入）
        dishFlavorMapper.deleteBydishId(dishDTO.getId());
        //为口味数据设置关联的菜品id
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }
    /**
     * 菜品起售停售
     *
     * @param status
     * @param id
     */
    @Transactional
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 获取所有菜品
     * @return
     */
    @Override
    public List<DishVO> showAllDish() {
        //从redis中查询所有菜品
        List<DishVO> dishVOList = redisTemplate.opsForList().range(KEY, 0, -1);
        if(dishVOList == null || dishVOList.size() == 0){
            //如果redis中没有数据，则从数据库中查询
            List<Dish> dishList = dishMapper.showAllDish(null);
            dishVOList = dishList.stream().map(dish -> {
                DishVO dishVO = new DishVO();
                BeanUtils.copyProperties(dish, dishVO);
                return dishVO;
            }).collect(Collectors.toList());
            //将查询到的菜品数据存储到redis中
            redisTemplate.opsForList().rightPushAll(KEY, dishVOList);
        }
        return dishVOList;
    }

}
